<?php
// ======================= Documentation ========================//
// Note：Order review for Paypal
// ==============================================================//

require 'global.php';
// 支付方式API信息, payment API info
$api_payment=$payment_method->get_row(3);
define('API_PAY_USERNAME', $api_payment['api_username']);
define('API_PAY_PASSWORD', $api_payment['api_password']);
define('API_PAY_KEY', $api_payment['api_key']);
define('API_PAY_ACCOUNT', $api_payment['account_no']);
//
require_once(ROOT."common/paypal/CallerService.php");
// 电邮相关 email
include(ROOT."common/mail_send.php");
$email_template=new DB(Temail_template,$conn);
// object order
$sales_order=new DB(Tsales_order,$conn);
$sales_order_detail=new DB(Tsales_order_detail,$conn);

$ref_no=encrypt(trim($_COOKIE['ref_no']),'decode');
$token = $_REQUEST['token'];
/* An express checkout transaction starts with a token, that 
   identifies to PayPal your transaction 
   In this example, when the script sees a token, the script 
   knows that the buyer has already authorized payment through 
   paypal.  If no token was found, the action is to send the buyer 
   to PayPal to first authorize payment */
if(! isset($token)){
/* The servername and serverport tells PayPal where the buyer
   should be directed back to after authorizing payment.
   In this case, its the local webserver that is running this script
   Using the servername and serverport, the return URL is the first
   portion of the URL that buyers will return to after authorizing payment */
   $serverName = $_SERVER['SERVER_NAME'];
   $serverPort = $_SERVER['SERVER_PORT'];
   $url=dirname('http://'.$serverName.':'.$serverPort.$_SERVER['REQUEST_URI']);

   $currencyCodeType = $_REQUEST['currency_sign'];
   $paymentType = 'Sale';
   $L_NAME0           = $_REQUEST['subject'];
   $L_AMT0            = $_REQUEST['total_price'];
   //$L_AMT0            = 0.01; // testing
   $L_QTY0            =	'1';

	/* The returnURL is the location where buyers return when a
	payment has been succesfully authorized.
	The cancelURL is the location buyers are sent to when they hit the
	cancel button during authorization of payment during the PayPal flow
	*/

	$returnURL =urlencode($url.'/api_paypal.php?currencyCodeType='.$currencyCodeType.'&paymentType='.$paymentType);
   //$cancelURL =urlencode("$url"); davee-0928
	$cancelURL =urlencode($baseurl);
 	/* Construct the parameter string that describes the PayPal payment
	the varialbes were set in the web form, and the resulting string
	is stored in $nvpstr */
   $itemamt = 0.00;
   $itemamt = $L_QTY0*$L_AMT0;
   $amt = $itemamt;
   $maxamt= $amt+25.00;
   $nvpstr='';
   /*
    * Setting up the Shipping address details
    */
   //$shiptoAddress = "&SHIPTONAME=$personName&SHIPTOSTREET=$SHIPTOSTREET&SHIPTOCITY=$SHIPTOCITY&SHIPTOSTATE=$SHIPTOSTATE&SHIPTOCOUNTRYCODE=$SHIPTOCOUNTRYCODE&SHIPTOZIP=$SHIPTOZIP";
   
   $nvpstr="&L_NAME0=".$L_NAME0."&L_AMT0=".$L_AMT0."&L_QTY0=".$L_QTY0."&AMT=".(string)$amt."&ITEMAMT=".(string)$itemamt."&CALLBACKTIMEOUT=8&ReturnUrl=".$returnURL."&CANCELURL=".$cancelURL ."&CURRENCYCODE=".$currencyCodeType."&PAYMENTACTION=".$paymentType;
   $nvpstr = $nvpHeader.$nvpstr;
 	/* Make the call to PayPal to set the Express Checkout token
	If the API call succeded, then redirect the buyer to PayPal
	to begin to authorize payment.  If an error occured, show the
	resulting errors */
   $resArray=hash_call("SetExpressCheckout",$nvpstr);
   $_SESSION['reshash']=$resArray;

   $ack = strtoupper($resArray["ACK"]);

   if($ack=="SUCCESS"){
			// Redirect to paypal.com here
			$token = urldecode($resArray["TOKEN"]);
			$payPalURL = PAYPAL_URL.$token;
			header("Location: ".$payPalURL);
	  } else  {
		 //Redirecting to APIError.php to display errors.
			//$location = "APIError.php";
			//header("Location: $location");
			echo 'Sorry, pay from paypal failed.#1';
			//print_r($resArray);
			exit;
		}
} else {
 /* At this point, the buyer has completed in authorizing payment
	at PayPal.  The script will now call PayPal with the details
	of the authorization, incuding any shipping information of the
	buyer.  Remember, the authorization is not a completed transaction
	at this state - the buyer still needs an additional step to finalize
	the transaction
	*/
   $token =urlencode($_REQUEST['token']);
 /* Build a second API request to PayPal, using the token as the ID to get the details on the payment authorization */
   $nvpstr="&TOKEN=".$token;
   $nvpstr = $nvpHeader.$nvpstr;
   @file_put_contents('log_paypal.txt', serialize($_REQUEST) );
 /* Make the API call and store the results in an array.  If the
	call was a success, show the authorization details, and provide
	an action to complete the payment.  If failed, show the error */
   $resArray=hash_call("GetExpressCheckoutDetails",$nvpstr);
   //$_SESSION['reshash']=$resArray;
   $ack = strtoupper($resArray["ACK"]);

   if($ack == 'SUCCESS' || $ack == 'SUCCESSWITHWARNING'){
			//equire_once "paypal/GetExpressCheckoutDetails.php";
			//Continue to Pay

		/* Gather the information to make the final call to
		   finalize the PayPal payment.  The variable nvpstr
		   holds the name value pairs
		   */
		$token = $resArray['TOKEN'] ? $resArray['TOKEN'] : urlencode($_REQUEST['token']);
		$paymentAmount = $resArray['AMT'] ? $resArray['AMT'] : urlencode($_REQUEST['paymentAmount']);
		$paymentType = urlencode($_REQUEST['paymentType']);
		$currCodeType = $resArray['CURRENCYCODE'] ? $resArray['CURRENCYCODE'] : urlencode($_REQUEST['currencyCodeType']);
		$payerID = $resArray['PAYERID'] ? $resArray['PAYERID'] : urlencode($_REQUEST['PayerID']);
		$serverName = urlencode($_SERVER['SERVER_NAME']);
		$payer=$resArray['EMAIL']; //  davee's
		$nvpstr='&TOKEN='.$token.'&PAYERID='.$payerID.'&PAYMENTACTION='.$paymentType.'&AMT='.$paymentAmount.'&CURRENCYCODE='.$currCodeType.'&IPADDRESS='.$serverName ;

		//echo 'Processing...please wait.';
		 /* Make the call to PayPal to finalize payment
			 If an error occured, show the resulting errors
		*/
		$resArray=hash_call("DoExpressCheckoutPayment",$nvpstr);
		/* Display the API response back to the browser.
		   If the response from PayPal was a success, display the response parameters'
		   If the response was an error, display the errors received using APIError.php.
		   */
		$ack = strtoupper($resArray["ACK"]);
		if($ack != 'SUCCESS' && $ack != 'SUCCESSWITHWARNING'){
			echo 'Sorry, pay from paypal failed. #3';
			//print_r($resArray);
			exit;
		 } #end if

		 //Update order status here, davee mark at 10/09
		$arr=array(
			'payer'=>$payer,
			'payer_id'=>$payerID,
			'order_status'=>2,
			'paid_time'=>date('Y-m-d H:i:s'),
		);
		if($sales_order->update($arr,'ref_no',$ref_no)){
			$order=$sales_order->get_row($ref_no,'ref_no'); // 单号
			// 加积分
			$customer->add_point_by_order($ref_no);
			// 更新级别
			$customer->update_grade($order['customer_id']);
			// // 发电邮 send email
			// $order=$sales_order->get_row($ref_no,'ref_no'); // 单号
			// $tem_currency_code=$arrcurrency[$order['currency_id']]['code'];  // 货币
			// $customer_id=$order['customer_id'];
			// $nickname=WEB_GUEST;
			// if($customer_id > 0) {
			// 	$tem=$customer->get_row($customer_id);
			// 	$nickname=$tem['nickname'];
			// }
			// // 构造订单详细条目, 发电邮使用
			// $str_order='
			// <style>
			// .ordert { line-height:1.2; }
			// .ordert td { padding: 4px 6px; }
			// </style>
			// <table cellpadding="0" cellspacing="0" width="660" class="ordert" style="border-collapse:collapse;">
			// <thead>
			// 	<tr>
			// 	<th style="border: 1px solid #888;">'.WEB_ITEM.'</th>
			// 	<th style="border: 1px solid #888;">'.WEB_UNIT_PRICE.'</th>
			// 	<th style="border: 1px solid #888;">'.WEB_PURCHASE_QUANTITY.'</th>
			// 	</tr>
			// </thead>
			// <tbody>';
			// $tem_items=$sales_order_detail->get_rows(1024,'sales_order_id',$order['id']);
			// foreach($tem_items as $tem_item){
			// 	$tem_product=$product->get_row($tem_item['product_id']);
			// 	$tem_pic=PRODUCT_PIC_HOST.$tem_product['small_pic'];
			// 	$tem_link=$baseurl.'product-'.$tem_product['id'].'.html';
			// 	$tem_name=str_cut($tem_product['name_'.$lang],PRODUCT_TITLE_DISPLAY_LENGTH,$lang);
			// 	$tem_price=$tem_item['unit_price'];
			// 	// variation
			// 	$str_var='';
			// 	if($tem_item['product_variation_id']){
			// 		$tem_var=$product_variation->get_row($tem_item['product_variation_id']);
			// 		if($tem_var['size']) $str_var.=$option_label[2].': '.$option_value[$tem_var['size']].' &nbsp; ';
			// 		if($tem_var['color']) $str_var.=$option_label[1].': '.$option_value[$tem_var['color']].' &nbsp; ';
			// 		if($tem_var['other1']) $str_var.=$option_label[3].': '.$option_value[$tem_var['other1']].' &nbsp; ';
			// 		if($tem_var['other2']) $str_var.=$option_label[4].': '.$option_value[$tem_var['other2']].' &nbsp; ';
			// 	}
			// 	$str_order.='<tr>
			// 		<td style="border: 1px solid #888;width:300px;"><div><a style="float:left;" href="'.$tem_link.'" target="_blank"><img src="'.$tem_pic.'"  width="60" style="padding: 0 8px 0 0;"  /></a><div class="name"><a href="'.$tem_link.'" target="_blank">'.$tem_name.'</a><br /><span style="color:#888">'.$str_var.'</span></div><div class="clear"></div></div></td>
			// 		<td style="border: 1px solid #888;"><strong class="price red">'.$tem_currency_code.' '.$tem_price.'</strong></td>
			// 		<td style="border: 1px solid #888;">'.$tem_item['quantity'].'</td>
			// 		</tr>';
			// }
			// $str_order.='<tbody></table>
			// <p>'.WEB_TOTAL_FOR_ITEMS.': '.$tem_currency_code.' '.$order['order_price'].'<br />
			// '.WEB_SHIPMENT_FEE.': '.$tem_currency_code.' '.$order['shipment_cost'].'<br />
			// '.WEB_ORDER_TOTAL.': '.$tem_currency_code.' '.$order['total_price'].'</p>';

			// // 邮件变量 email variables
			// $order_txt='<br />'; // 订单文本化, 用于发邮件, order in email
			// $order_txt.=WEB_ORDER_REF_NO.': '.$ref_no.'<br />';
			// $order_txt.=$str_order;
			// $order_txt.=WEB_ORDERED_TIME.': '.date('Y-m-d').'<br />';

			// $var_email=array(
			// 	'%nickname%'=>$nickname,
			// 	'%date%'=>date('Y-m-d'),
			// 	'%datetime%'=>date('Y-m-d H:i:s'),
			// 	'%url%'=>$baseurl,
			// 	'%company%'=>$config['SITE_COMPANY_'.LANG],
			// 	'%order%'=>$order_txt,
			// 	'%order_ref_no%'=>$ref_no,
			// );
			// // replace vars 替换变量
			// $arr_email = $email_template->get_row(3); // id=3 客户邮件
			// $arr_email_admin = $email_template->get_row(4); // id=4 管理员邮件

			// $subject=$arr_email['subject_'.$lang];
			// $subject_admin=$arr_email_admin['subject_'.$lang];
			// $body=$arr_email['content_'.$lang];
			// $body_admin=$arr_email_admin['content_'.$lang];
			// foreach ($var_email as $key => $value) {
			// 	$subject=str_replace($key, $value, $subject);
			// 	$body=str_replace($key, $value, $body);
			// 	$subject_admin=str_replace($key, $value, $subject_admin);
			// 	$body_admin=str_replace($key, $value, $body_admin);
			// }

			// $body='<!doctype html><html>
			// <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			// <title>'.$subject.'</title></head>
			// <body>'.$body.'</body></html>';
			// $body_admin='<!doctype html><html>
			// <head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
			// <title>'.$subject_admin.'</title></head>
			// <body>'.$body_admin.'</body></html>';
			// $arr=array(
			// 	'to'=>array($order['email']),
			// 	'subject'=>$subject,
			// 	'body'=>$body,
			// 	'host'=>EMAIL_HOST,
			// 	'account'=>EMAIL_ACCOUNT,
			// 	'password'=>EMAIL_PASSWORD,
			// 	'port'=>EMAIL_PORT,
			// 	'name'=>EMAIL_NAME,
			// 	'ssl'=>EMAIL_SSL,
			// );
			// //pre($arr);
			// if(mail_send($arr)) $k=1; // 发信给顾客 send email to customer

			// $email_admin_txt=DAILY_SALES_ORDER_RECIPIENT_EMAILS;
			// $tem_array=explode(',', $email_admin_txt);
			// $email_admin=array();
			// foreach($tem_array as $val) $email_admin[]=trim($val);
			// $arr_admin=array(
			// 	'to'=>$email_admin,
			// 	'subject'=>$subject_admin,
			// 	'body'=>$body_admin,
			// 	'host'=>EMAIL_HOST,
			// 	'account'=>EMAIL_ACCOUNT,
			// 	'password'=>EMAIL_PASSWORD,
			// 	'port'=>EMAIL_PORT,
			// 	'name'=>EMAIL_NAME,
			// 	'ssl'=>EMAIL_SSL,
			// );
			// //pre($arr);
			// if(mail_send($arr_admin)) $k=1; // 发信给管理员 send email to admin
			// email end
			// 需要根据订单更新库存
			//$product->update_stock_by_order($ref_no);
			//$davee=1;
			//echo "pay status updated"; 
			//Redirect to succeed page 
			cry(WEB_ORDER_ONLINE_PAID_SUCCESS,'myorder.php');
		}
		session_unset();
		session_destroy();
	  } else  {
		//Redirecting to APIError.php to display errors.
		//$location = "APIError.php";
		//header("Location: $location");
		echo 'Sorry, pay from paypal failed.#2';
		//print_r($resArray);
		exit;
	  }
}
//echo $cname.$cemail.$bid;

?>